import 'package:bilibili/gen/assets.gen.dart';
import 'package:bilibili/page/comment_page.dart';
import 'package:bilibili/page/introduction_page.dart';
import 'package:bilibili/util/screen_utils.dart';
import 'package:bilibili/widget/hi_barrage_send_widget.dart';
import 'package:bilibili/widget/hi_tab_bar.dart';
import 'package:bilibili/widget/navigation_bar.dart';
import 'package:flutter/material.dart';
import 'package:hi_barrage/hi_barrage_view.dart';
import 'package:hi_common/util/logger.dart';
import 'package:hi_net/http/core/hi_error.dart';
import 'package:hi_video/video_view.dart';
import 'package:lottie/lottie.dart';
import '../const/Const.dart';
import '../http/dao/video_detail_dao.dart';
import '../http/model/video_detail_mo.dart';
import '../http/model/video_model.dart';
import '../util/toast.dart';
import '../widget/hi_barrage_widget.dart';

class VideoDetailPage extends StatefulWidget {
  final VideoModel? videoModel;
  final String vid;

  const VideoDetailPage({this.videoModel, required this.vid, super.key});

  @override
  State<StatefulWidget> createState() {
    return _VideoDetailPageState();
  }
}

class _VideoDetailPageState extends State<VideoDetailPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  final List<String> _tabs = ["简介", "评论"];
  late VideoModel? videoModel;
  VideoDetailMo? videoDetailMo;
  String content = "点我发弹幕";
  final _barrageKey = GlobalKey<HiBarrageViewState>();

  @override
  void initState() {
    _tabController = TabController(length: _tabs.length, vsync: this);
    super.initState();
    videoModel = widget.videoModel;
    _loadDetail(widget.vid);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: _buildBody());
  }

  _buildBody() {
    if (videoModel == null) {
      return Center(
        child: Lottie.asset(Assets.loading),
      );
    } else {
      var screenWidth = MediaQuery.of(context).size.width;
      var playerHeight = screenWidth / (16.0 / 9.0);
      return Column(children: [
        const BiliNavigationBar(
          statusStyle: StatusStyle.LIGHT_CONTENT,
          color: Colors.black,
          height: 0,
        ),
        VideoView(
            url: videoModel!.url,
            vid: videoModel!.vid,
            cover: videoModel!.cover,
            autoPlay: true,
            width: screenWidth,
            height: playerHeight,
            barrageUI: HiBarrageView(
              autoPlay: true,
              key: _barrageKey,
              width: screenWidth,
              height: playerHeight,
              vid: videoModel!.vid,
              headers: Const.wsHeader(),
            )),
        _buildTabBar(),
        _buildPageView(videoModel!)
      ]);
    }
  }

  _buildTabBar() {
    return Material(
      elevation: 5,
      shadowColor: Colors.grey[100],
      child: Container(
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 20),
        height: 39,
        width: double.infinity,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [_buildBar(), _buildBarrageBtn()],
        ),
      ),
    );
  }

  _buildBarrageBtn() {
    return Padding(
      padding: const EdgeInsets.only(right: 20),
      child: HiBarrageWidget(
        initStatus: true,
        content: content,
        onToggle: (open) {
          logger.i("open :$open");
          if (open) {
            _barrageKey.currentState?.play();
          } else {
            _barrageKey.currentState?.paused();
          }
        },
        onClick: () {
          setState(() {
            content = "弹幕发送中";
            Navigator.push(
              context,
              PageRouteBuilder(
                  pageBuilder: (BuildContext context,
                          Animation<double> animation,
                          Animation<double> secondaryAnimation) =>
                      const HiBarrageSendWidget(),
                  transitionsBuilder:
                      (context, animation, secondaryAnimation, child) {
                    return FadeTransition(opacity: animation, child: child);
                  },
                  opaque: false),
            ).then((message) {
              setState(() {
                content = "点我发弹幕";
              });
              _barrageKey.currentState?.send(message);
            });
          });
        },
      ),
    );
  }

  _buildBar() {
    return HiTabBar(
      tabs: _tabs.map((tab) {
        return Tab(text: tab);
      }).toList(),
      controller: _tabController,
    );
  }

  _buildPageView(VideoModel videoModel) {
    return Flexible(
        child: TabBarView(controller: _tabController, children: [
      IntroductionPage(
        videoInfo: videoModel,
        model: videoDetailMo,
      ),
      const CommentPage()
    ]));
  }

  void _loadDetail(String vid) async {
    try {
      VideoDetailMo data = await VideoDetailDao.get(vid);
      setState(() {
        videoDetailMo = data;
        videoModel = data.videoInfo;
      });
    } on NeedLogin catch (e) {
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      showWarnToast(e.message);
    } catch (e) {
      logger.e(e);
    }
  }
}
